﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Ninject;
using Meraz.Core.Repositories;
using Meraz.Core.Model;

namespace Meraz.Core.Commands
{
    public interface ISaveIssueCommand { 
        IIssueRepository IssueRepository { get; set; }
        ITopicRepository TopicRepository { get; set; }
        Issue Execute(int postID, string topicName, AffectiveFrameType affectiveFrameType);
    }
    public class SaveIssueCommand : BaseCommand, ISaveIssueCommand
    {
        [Inject]
        public IIssueRepository IssueRepository { get; set; }
        [Inject]
        public ITopicRepository TopicRepository { get; set; }

        public Issue Execute(int postID, string topicName, AffectiveFrameType affectiveFrameType)
        {
            Issue issue = IssueRepository.GetByName(topicName);
            if (issue == null)
            {
                //the issue does not exist
                //check if topic exists
                Topic topic = TopicRepository.Get(topicName);
                if (topic == null)
                {
                    topic = new Topic();
                    TopicRepository.Add(topic);
                    topic.Name = topicName;
                }
                issue = new Issue();
                IssueRepository.Add(issue);
                issue.Topic = topic;
                issue.PostID = postID;
            }
            issue.AffectiveFrameType = affectiveFrameType;
            Commit();
            return issue;
        }
    }
}
